package com.autumn.gateway.server.controllers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.autumn.common.api.web.vo.ApiObjectResponse;

/**
 * Api错误处理器
 * 
 * @author 老码农
 *         <p>
 *         Description
 *         </p>
 * @date 2017-12-19 00:23:50
 */
@RestController
@Configuration
public class ApiResponseController extends AbstractErrorController {

	/**
	 * 
	 */
	public ApiResponseController() {
		super(new DefaultErrorAttributes());
	}

	/**
	 * api 根 url
	 */
	public final static String ERROR_RUL = "/api/error";

	@Override
	public String getErrorPath() {
		return ERROR_RUL;
	}
	
	/**
	 * 获取错误地址
	 * 
	 * @param request
	 * @return 2017-12-07 11:18:13
	 */
	@GetMapping(ERROR_RUL)
	public ApiObjectResponse error(HttpServletRequest request) {
		HttpStatus status = getStatus(request);
		Map<String, Object> body = getErrorAttributes(request, false);
		String message = "未知异常";
		String details = "";
		if (body != null) {
			Object value;
			value = body.get("message");
			if (value != null) {
				message = value.toString();
			}
			value = body.get("path");
			if (value != null) {
				details = value.toString();
			}
		}
		return ApiObjectResponse.error(status.value(), message, details);
	}
	
	
	/**
	 * 重定向
	 * 
	 * @return
	 */
	@Bean
	public EmbeddedServletContainerCustomizer containerCustomizer() {
		return (container -> {
			ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, ERROR_RUL);
			ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, ERROR_RUL);
			ErrorPage error405Page = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, ERROR_RUL);
			ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, ERROR_RUL);
			container.addErrorPages(error401Page, error404Page, error405Page, error500Page);
		});
	}

}
